package main

import (
	"fmt"
	"time"
)

func main() {
	useTimer()
	cancelTimer()
	rangeTicker()
}

/**
用于单线程的等待，效果同time.sleep
*/
func useTimer() {
	fmt.Println("Starts @ ", time.Now())
	timer1 := time.NewTicker(time.Second * 2)
	fmt.Println("Ticket @ ", <-timer1.C)
	fmt.Println("Timer 1 expired")
}

/**
等待过程总可以stop，
*/
func cancelTimer() {
	timer2 := time.NewTicker(time.Second)
	go func() {
		<-timer2.C
		// never execute this
		fmt.Println("Timer 2 expired")
	}()
	timer2.Stop()
	fmt.Println("Timer 2 stopped")
}

/**
设定500ms发送一次tick事件
接收ticker事件
*/
func rangeTicker() {
	ticker := time.NewTicker(time.Millisecond * 500)

	go func() {
		for t := range ticker.C {
			fmt.Println("Tick at ", t)
		}
	}()
	time.Sleep(time.Millisecond * 1600)
	ticker.Stop()
	fmt.Println("Ticker stopped")
}
